<template>
  <view class="chat">
    <!-- 顶部标题 -->
    <view class="top-tabbar">
      <scroll-view class="scroll-tabs" scroll-x="true">
        <view class="tab" v-for="(expert, index) in experts" :key="index" @click="switchTab(expert,index)" :class="{ active: currentTab === index }">
          <image class="tab-icon" :src="expert.expertImageUrl"></image>
          <text class="tab-text">{{ expert.expertName }}</text>
        </view>
      </scroll-view>
    </view>
	<view class="select">
		<button @click="init" class="init-btn">{{state}}</button>
		<button @click="exit" class="init-btn">下线</button>
		<button @click="article" class="init-btn">文章</button>
		<button @click="showIntroduction" class="init-btn">介绍</button>
		</view>
  
    <!-- 聊天主体 -->
    <scroll-view :style="{ height: `${windowHeight - inputHeight - 180}rpx` }"
                 id="scrollview"
                 scroll-y="true"
                 :scroll-top="scrollTop"
                 class="scroll-view">
      <view id="msglistview" class="chat-body">
		 
        <!-- 聊天记录 -->
        <view v-for="(item, index) in mseNow" :key="index">
          <!-- 自己发的消息 -->
          <view class="item self" v-if="item.userContent != ''">
            <view class="content right">{{ item.userContent }}</view>
            <image class="avatar" :src="item.image"></image>
          </view>
          <!-- 机器人发的消息 -->
          <view class="item Ai" v-if="item.botContent != ''">
            <image class="avatar" :src="item.expertImageUrl"></image>
            <view class="content left">{{ item.botContent }}</view>
          </view>
		  
        </view>
      </view>
    </scroll-view>

    <!-- 底部消息发送栏 -->
    <view class="chat-bottom" :style="{ height: `${inputHeight}rpx` }">
      <view class="send-msg" :style="{ bottom: `${keyboardHeight}rpx` }">
        <view class="uni-textarea">
          <textarea v-model="chatMsg"
                    maxlength="300"
                    confirm-type="send"
                    @confirm="handleSend"
                    placeholder="快来聊天吧~"
                    :show-confirm-bar="false"
                    :adjust-position="false"
                    @linechange="sendHeight"
                    @focus="focus" @blur="blur"
                    auto-height></textarea>
        </view>
		
        <button @click="handleSend" class="send-btn">发送</button>
      </view>
    </view>
	 <!-- 弹出框组件 -->
	    <uni-popup ref="popup" type="center">
	      <view class="popup-content">
	        <text class="popup-title">专家介绍</text>
			<view>
				<text class="popup-description">{{ expertNow.expertDesc }}</text>
			</view>        
	        <button class="popup-close" @click="closePopup">关闭</button>
	      </view>
	    </uni-popup>
	 
  </view>

</template>

<script>
import msg from '../msg';
import { getAllExperts } from '@/api/plant/plant.js';

export default {
  data() {
    return {
		state:"上线",
	  currentTab: 0, 
      base: "@/static/fss-image/",
      sokectTask: null,
      reconnectInterval: 3000, // 重连间隔时间（毫秒）
      heartbeatInterval: null, // 心跳定时器
      experts: [
        {
          expertDesc: "",
          expertId: 0,
          expertImageUrl: "",
          expertName: "",
          loginIp: "",
        },
      ],
      expertNow: {},
      myName: 0,
      mseNow: [
        {
          targetName: "",
          botContent: "",
          userContent: "",
          image: "",
        },
      ],
      keyboardHeight: 0, // 键盘高度
      bottomHeight: 0, // 底部消息发送框高度
      scrollTop: 0, // 滚动距离
      chatMsg: "", // 发送的消息
      msgList: [
        {
          targetName: "",
          botContent: "",
          userContent: "",
          image: "",
        },
      ],
      tabs: [
        { icon: "/static/fss-image/qj.jpg", text: "聊天" },
      ],
      currentTab: null,
    };
  },
  computed: {
    windowHeight() {
      return this.rpxTopx(uni.getSystemInfoSync().windowHeight);
    },
    // 输入框的总高度 = 键盘高度 + 底部栏的高度
    inputHeight() {
      return this.bottomHeight + this.keyboardHeight;
    },
  },
  onLoad() {
    uni.onKeyboardHeightChange(res => {
      this.keyboardHeight = this.rpxTopx(res.height);
      if (this.keyboardHeight < 0) this.keyboardHeight = 0;
    });
  },
  methods: {
	  article(){
		uni.navigateTo({
			url: '/pages/plant/article/article'
		});
  
	  },
	  exit(){
		   this.state="下线"
		  this.sokectTask.close()
	  },
	  init(){
		  this.state="已上线"
     this.sendMessage(JSON.stringify(this.myName));
	  },
    rpxTopx(px) {
      let deviceWidth = uni.getSystemInfoSync().windowWidth;
      let rpx = (750 / deviceWidth) * Number(px);
      return Math.floor(rpx);
    },

    // 发送消息
    handleSend() {
      if (!this.chatMsg || !/^\s+$/.test(this.chatMsg)) {
        let obj = {
          targetName: this.expertNow.expertName,
          botContent: "",
          userContent: this.chatMsg,
          image: "/static/fss-image/qj.jpg",
        };
		// this.msgList=this.mseNow
		// let a=this.msgList[0].targetName
		//         this.msgList=this.mseNow;
		this.msgList=this.mseNow;
		this.msgList[0].targetName=this.expertNow.expertName;
        this.msgList.push(obj);
		this.mseNow=this.msgList;
		// for(let i=0;i<msg.allMsg.length;i++)
		// {
		// 	console.log(this.expertNow.expertName)
			
		// 	console.log(this.mseNow)
		// 	if(this.expertNow.expertName===msg.allMsg[i].expertName)
		// 	{
		// 		msg.allMsg[i].msgList=this.mseNow;
		// 	}
		// }
		console.log(msg)
		console.log(this.msgList)
        this.sendMessage(JSON.stringify(this.msgList));
        this.chatMsg = '';
        this.scrollToBottom();
      } else {
        this.$modal.showToast('不能发送空白消息');
      }
    },

    // 切换标签
    switchTab(expert,index) {
		let p=0,q=0;
		console.log(this.expertNow.expertName)
		console.log(expert.expertName)
		for(let i=0;i<msg.allMsg.length;i++)
		{
			if(this.expertNow.expertName===msg.allMsg[i].expertName)
			{
				p=1;
				msg.allMsg[i].msgList=this.mseNow;
			}
		}

		console.log(p)
		if(p===0){
				let tmp={
					expertName:'',
					msgList:this.mseNow
					// [ {
			  //       targetName: "",
			  //       botContent: "",
			  //       userContent: "",
			  //       image: "",
			  //     },]
						}
					tmp.expertName= this.expertNow.expertName
					msg.allMsg.push(tmp)
		}
		for(let i=0;i<msg.allMsg.length;i++)
		{
			if(expert.expertName===msg.allMsg[i].expertName)
			{
				q=1;
				this.mseNow=msg.allMsg[i].msgList;
				break;
			}
		}
		console.log(p)
		if(q===0){
				this.mseNow=[{
          targetName: expert.expertName,
          botContent: "",
          userContent: "",
          image: "",
        },]
		}
		// if(es===0)
		// {
		// 	let tmp={
		// 		expertName:'',
		// 		msgList:[ {
  //         targetName: "",
  //         botContent: "",
  //         userContent: "",
  //         image: "",
  //       },]
		// 	}
		// 	tmp.expertName= expert.expertName
		// 	msg.allMsg.push(tmp)
		// }
		// console.log(es)
		console.log(msg)
		// this.mseNow=[ {
  //         targetName: "",
  //         botContent: "",
  //         userContent: "",
  //         image: "",
  //       }]
		this.currentTab=index
      this.expertNow = expert;
      this.msgList[0].targetName = expert.expertName;
      this.mseNow[0].targetName = expert.expertName;
    },
	
	       //获取用户信息
	       async getExperts() {
	         try {
	           const data = await getAllExperts();
	           // 为每个 expert 的 expertImageUrl 字段加上 baseUrl
	           const baseUrl = "http://localhost:8080"; 
	           this.experts = data.map(expert => ({
	             ...expert, 
	             expertImageUrl: baseUrl + expert.expertImageUrl
				
	           }));
	           this.expertNow = this.experts[0];
			  
	         } catch (error) {
	           console.error('获取数据失败:', error);
	         }
	       },
		  


    // 监视聊天发送栏高度
    sendHeight() {
      setTimeout(() => {
        let query = uni.createSelectorQuery();
        query.select('.send-msg').boundingClientRect();
        query.exec(res => {
          this.bottomHeight = this.rpxTopx(res[0].height);
        });
      }, 10);
    },

    // 滚动至聊天底部
    scrollToBottom(e) {
      setTimeout(() => {
        let query = uni.createSelectorQuery().in(this);
        query.select('#scrollview').boundingClientRect();
        query.select('#msglistview').boundingClientRect();
        query.exec((res) => {
          if (res[1].height > res[0].height) {
            this.scrollTop = this.rpxTopx(res[1].height - res[0].height);
          }
        });
      }, 15);
    },

    focus() {
      this.scrollToBottom();
    },

    blur() {
      this.scrollToBottom();
    },

    // 连接 WebSocket
    sendMessage(message) {
      this.sokectTask.send({
        data: message,
        success: function(res) {
          console.log('Data sent successfully', res);
        },
        fail: function(err) {
          console.error('Failed to send data', err);
        },
      });
    },
	// 显示专家介绍
	    showIntroduction() {
	      this.$refs.popup.open();
	    },
	    // 关闭对话框
	    closePopup() {
	      this.$refs.popup.close();
	    },
  },
  beforeMount() {
    this.sokectTask = uni.connectSocket({
      url: 'ws://localhost:8080/websocket',
      success: function(res) {
        console.log('WebSocket connection opened', res);
      },
      fail: function(err) {
        console.error('WebSocket connection failed', err);
      },
    });
  },
 onShow() {
     this.getExperts();
	let that=this
    this.myName = this.$store.state.user.name;
	// for(let i=0;i<this.experts.length;i++)
	// {
	// 	if(this.experts[i].expertName===this.myName)
	// 	{
	// 		this.expertNow=this.experts[i]
	// 	}
	// }
    
  //this.sendMessage(this.myName)
 
 // this.sokectTask.onOpen(() => {
 //      console.log('WebSocket connection opened');
 //      this.sendMessage(JSON.stringify(this.myName));
 //    });
    this.sokectTask.onMessage(function(res) {
      console.log("---------------------------");
      console.log(JSON.parse(res.data));
      that.mseNow = JSON.parse(res.data);
    });
  },
};
</script>




 
<style lang="css" scoped>
	/* 公共样式 */
	view, button, text, input, textarea {
	  margin: 0;
	  padding: 0;
	  box-sizing: border-box;
	}
	
	/* 顶部横向滑动区域 */
	.top-tabbar {
	  width: 100%;
	  height: 138rpx; /* 调整为新的高度 */
	  line-height: 120rpx; /* 保持与高度一致 */
	  display: flex;
	  align-items: center;
	  background-color: #d6d6d6;
	  border-bottom: 1rpx solid #E0E0E0;
	}
	
	.scroll-tabs {
	  display: flex;
	  white-space: nowrap;
	  width: 100%;
	  overflow-x: auto;
	  -webkit-overflow-scrolling: touch;
	   padding-bottom: 0rpx;
	}
	
	.scroll-tabs::-webkit-scrollbar {
	  display: none;
	  width: 0 !important;
	  height: 0 !important;
	  -webkit-appearance: none;
	  background: transparent;
	  color: transparent;
	}
	
	.tab {
	  display: inline-flex;
	  flex-direction: column;
	 align-items: center;
	  justify-content: flex-end;
	  padding: 0 30rpx;
	  font-size: 24rpx;
	  font-weight: 500;
	  color: #333333;
	  cursor: pointer;
	  padding-bottom: 0rpx;
	}
	
	.tab.active {
	  color: #4F7DF5;
	  border-bottom: 4rpx solid #4F7DF5;
	}
	
	.tab-icon {
	  width: 65rpx;
	  height: 65rpx;
	  margin-top: 20rpx;
	  margin-bottom: 0rpx;
	  border-radius: 50%; /* 设置为圆形 */
	}

	
	.tab-text {
		 line-height: 1;
		 margin-top: 37rpx;
	  font-size: 25rpx;
	}
	
	/* 聊天消息 */
	.chat {
	  background-color: #F6F6F6;
	  height: calc(100% - 120rpx - 100rpx); /* 调整为新的高度 */
	}
	
	.scroll-view {
	  background-color: #F6F6F6;
	  height: calc(100% - 120rpx - 100rpx); /* 调整为新的高度 */
	}
	
	.scroll-view::-webkit-scrollbar {
	  display: none;
	  width: 0 !important;
	  height: 0 !important;
	  -webkit-appearance: none;
	  background: transparent;
	  color: transparent;
	}
	
	.chat-body {
	  display: flex;
	  flex-direction: column;
	  padding-top: 23rpx;
	}
	
	.item {
	  display: flex;
	  padding: 23rpx 30rpx;
	}
	
	.item.self {
	  justify-content: flex-end;
	}
	
	.right {
	  background-color: #C2DCFF;
	}
	
	.left {
	  background-color: #FFFFFF;
	}
	
	.right::after {
	  position: absolute;
	  display: inline-block;
	  content: '';
	  width: 0;
	  height: 0;
	  left: 100%;
	  top: 10px;
	  border: 12rpx solid transparent;
	  border-left: 12rpx solid #C2DCFF;
	}
	
	.left::after {
	  position: absolute;
	  display: inline-block;
	  content: '';
	  width: 0;
	  height: 0;
	  top: 10px;
	  right: 100%;
	  border: 12rpx solid transparent;
	  border-right: 12rpx solid #FFFFFF;
	}
	
	.content {
	  position: relative;
	  max-width: 486rpx;
	  border-radius: 8rpx;
	  word-wrap: break-word;
	  padding: 24rpx 24rpx;
	  margin: 0 24rpx;
	  border-radius: 5px;
	  font-size: 32rpx;
	  font-family: PingFang SC;
	  font-weight: 500;
	  color: #333333;
	  line-height: 42rpx;
	}
	
	.avatar {
	  display: flex;
	  justify-content: center;
	  width: 78rpx;
	  height: 78rpx;
	  background: #4F7DF5;
	  border-radius: 50rpx;
	  overflow: hidden;
	}
	
	.avatar image {
	  align-self: center;
	}
	
	/* 底部聊天发送栏 */
	.chat-bottom {
	  width: 100%;
	  height: 100rpx;
	  background: #F4F5F7;
	  transition: all 0.1s ease;
	}
	
	.send-msg {
	  display: flex;
	  align-items: flex-end;
	  padding: 16rpx 30rpx;
	  width: 100%;
	  min-height: 177rpx;
	  position: fixed;
	  bottom: 0;
	  background: #fff;
	  transition: all 0.1s ease;
	}
	
	.uni-textarea {
	  padding-bottom: 70rpx;
	}
	
	.uni-textarea textarea {
	  width: 537rpx;
	  min-height: 75rpx;
	  max-height: 500rpx;
	  background: #f1f1f1;
	  border-radius: 40rpx;
	  font-size: 32rpx;
	  font-family: PingFang SC;
	  color: #333333;
	  line-height: 74rpx;
	  padding: 5rpx 8rpx;
	  text-indent: 30rpx;
	}
	
	.send-btn {
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  margin-bottom: 76rpx;
	  margin-left: 25rpx;
	  width: 120rpx;
	  height: 75rpx;
	  background: #4F7DF5;
	  color: #fff;
	}
    .init-btn{
		display: fix;
		z-index: 100;
		align-items: center;
		justify-content: center;
		margin-top: 25px;
		margin-bottom: 76rpx;
		margin-left:55rpx;
		width: 120rpx;
		height: 75rpx;
		background: #ffaaff;
		color: #fff;
	}
	.select{
		height: 90px;
		margin-top: 5px;
		margin-left: 3px;
		border-radius: 15px;
		background-color: #55aa7f;
		display: flex;
		width: 98%;
	}
	.popup-content {
		  background-color: #fff; /* 白色背景 */
		  /* padding: 20px; */
		  border-radius: 10px;
		  width: 500rpx;
		  height: 500rpx;
		  /* max-width: 400px; */ /* 最大宽度 */
		  text-align: center;
		  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 阴影效果 */
		}
		
		.popup-title {
		  font-size: 18px;
		  font-weight: bold;
		  margin-bottom: 10px;
		}
		
		.popup-description {
		  font-size: 14px;
		  margin-bottom: 20px;
		}
		
		.popup-close {
		  background-color: #007aff;
		  color: #fff;
		  margin-top: 400rpx;
		  border-radius: 5px;
		  border: none;
		  cursor: pointer;
		}
		
		.popup-close:hover {
		  background-color: #0056b3;
		}
	 </style>
 